The year 518 is significantly more underground than your history books implied. Either that, or you've arrived in a vast cavern network under the North Pole.

After exploring a little, you discover a long tunnel that contains a row of small pots as far as you can see to your left and right. A few of them contain plants - someone is trying to grow things in these geothermally-heated caves.

The pots are numbered, with 0 in front of you. To the left, the pots are numbered -1, -2, -3, and so on; to the right, 1, 2, 3.... Your puzzle input contains a list of pots from 0 to the right and whether they do (#) or do not (.) currently contain a plant, the initial state. (No other pots currently contain plants.) For example, an initial state of #..##.... indicates that pots 0, 3, and 4 currently contain plants.

Your puzzle input also contains some notes you find on a nearby table: someone has been trying to figure out how these plants spread to nearby pots. Based on the notes, for each generation of plants, a given pot has or does not have a plant based on whether that pot (and the two pots on either side of it) had a plant in the last generation. These are written as LLCRR => N, where L are pots to the left, C is the current pot being considered, R are the pots to the right, and N is whether the current pot will have a plant in the next generation. For example:

A note like ..#.. => . means that a pot that contains a plant but with no plants within two pots of it will not have a plant in it during the next generation.
A note like ##.## => . means that an empty pot with two plants on each side of it will remain empty in the next generation.
A note like .##.# => # means that a pot has a plant in a given generation if, in the previous generation, there were plants in that pot, the one immediately to the left, and the one two pots to the right, but not in the ones immediately to the right and two to the left.
It's not clear what these plants are for, but you're sure it's important, so you'd like to make sure the current configuration of plants is sustainable by determining what will happen after 20 generations.

For example, given the following input:

initial state: #..#.#..##......###...###

...## => #
..#.. => #
.#... => #
.#.#. => #
.#.## => #
.##.. => #
.#### => #
#.#.# => #
#.### => #
##.#. => #
##.## => #
###.. => #
###.# => #
####. => #
For brevity, in this example, only the combinations which do produce a plant are listed. (Your input includes all possible combinations.) Then, the next 20 generations will look like this:

                 1         2         3     
       0         0         0         0     
 0: ...#..#.#..##......###...###...........
 1: ...#...#....#.....#..#..#..#...........
 2: ...##..##...##....#..#..#..##..........
 3: ..#.#...#..#.#....#..#..#...#..........
 4: ...#.#..#...#.#...#..#..##..##.........
 5: ....#...##...#.#..#..#...#...#.........
 6: ....##.#.#....#...#..##..##..##........
 7: ...#..###.#...##..#...#...#...#........
 8: ...#....##.#.#.#..##..##..##..##.......
 9: ...##..#..#####....#...#...#...#.......
10: ..#.#..#...#.##....##..##..##..##......
11: ...#...##...#.#...#.#...#...#...#......
12: ...##.#.#....#.#...#.#..##..##..##.....
13: ..#..###.#....#.#...#....#...#...#.....
14: ..#....##.#....#.#..##...##..##..##....
15: ..##..#..#.#....#....#..#.#...#...#....
16: .#.#..#...#.#...##...#...#.#..##..##...
17: ..#...##...#.#.#.#...##...#....#...#...
18: ..##.#.#....#####.#.#.#...##...##..##..
19: .#..###.#..#.#.#######.#.#.#..#.#...#..
20: .#....##....#####...#######....#.#..##.
The generation is shown along the left, where 0 is the initial state. The pot numbers are shown along the top, where 0 labels the center pot, negative-numbered pots extend to the left, and positive pots extend toward the right. Remember, the initial state begins at pot 0, which is not the leftmost pot used in this example.

After one generation, only seven plants remain. The one in pot 0 matched the rule looking for ..#.., the one in pot 4 matched the rule looking for .#.#., pot 9 matched .##.., and so on.

In this example, after 20 generations, the pots shown as # contain plants, the furthest left of which is pot -2, and the furthest right of which is pot 34. Adding up all the numbers of plant-containing pots after the 20th generation produces 325.

After 20 generations, what is the sum of the numbers of all pots which contain a plant?

In [1]:
def evolve(lines):
    _, status = next(lines).split(':')
    status = {i: c for i, c in enumerate(status.strip())}
    next(lines)
    notes = [n.replace(' ', '').strip().split("=>") for n in lines]
    
    min_pos, max_pos = 0, len(status)-1
    yield min_pos, max_pos, status 
    while True:
        changes = {}
        for p, n in notes:
            p = [c for c in p]
            for i in range(min_pos-2, max_pos+2+1):
                if [status.get(i+j, '.') for j in [-2,-1,0,1,2]] == p:
                    changes[i] = n
        
        for p, n in changes.items():
            status[p] = n
            if n != '.':
                if p < min_pos:
                    min_pos = p
                if p > max_pos:
                    max_pos = p
           
        for p in range(min_pos, max_pos+1):
            if p not in changes:
                status[p] = '.'
                
        while status[min_pos] == '.':
            min_pos += 1
            
        while status[max_pos] == '.':
            max_pos -= 1
        
        yield min_pos, max_pos, status 
    
def sum_after(g, evolution, shift=0):    
    _,_,status = next(evolution)
    for _ in range(g):
        _,_,status = next(evolution)
        
    return sum(i+shift for i, v in status.items() if v == '#')

In [2]:
open("input/day12example.txt") |> evolve |> sum_after$(20)


Out[2]:
325

In [3]:
open("input/day12.txt") |> evolve |> sum_after$(20)


Out[3]:
3248
--- Part Two ---
You realize that 20 generations aren't enough. After all, these plants will need to last another 1500 years to even reach your timeline, not to mention your future.

After fifty billion (50000000000) generations, what is the sum of the numbers of all pots which contain a plant?

In [4]:
def find_first_cycle(generation):
    g = 0
    seen = {}
    min_pos, max_pos, status = next(generation)    
    status_str = "".join([status.get(p, '.') for p in range(min_pos, max_pos+1)])
    while status_str not in seen:
        seen[status_str] = g        
        g += 1        
        min_pos, max_pos, status = next(generation)            
        status_str = "".join([status.get(p, '.') for p in range(min_pos, max_pos+1)])
        
    return g, seen[status_str]

In [5]:
# Returns first generation with same status and the when it was seen.
open("input/day12.txt") |> evolve |> find_first_cycle


Out[5]:
(101, 100)

In [6]:
# Observe that the status is the same but the positions are
# shifted one position at each iteration
with open("input/day12.txt") as fd:
    generations = iter(evolve(fd))
    for g in range(110):
        minp, maxp, status = next(generations)
        if g > 99:
            print(g, minp, maxp)


100 2 198
101 3 199
102 4 200
103 5 201
104 6 202
105 7 203
106 8 204
107 9 205
108 10 206
109 11 207

In [7]:
# So we compute the sum but adding a shift
open("input/day12.txt") |> evolve |> sum_after$(100, shift=(50000000000 - 100))


Out[7]:
4000000000000